package com.example.service.impl;

import com.example.entity.PointDefend;
import com.example.entity.PointFlow;
import com.example.entity.training.TrainingPlanDetail;
import com.example.mapp.MessageNoticeMapp;
import com.example.mapp.PointFlowMapp;
import com.example.mapp.SysUserMapp;
import com.example.mapp.TrainingPlanDetailMapp;
import com.example.service.TrainingPlanDetailService;
import com.example.util.DateUtils;
import com.example.util.ResultUtil;
import com.example.util.SystemPointUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TrainingPlanDetailServiceImpl  implements TrainingPlanDetailService {
    private final static Logger logger = LoggerFactory.getLogger(TrainingPlanDetailServiceImpl.class);
    @Autowired
    TrainingPlanDetailMapp trainingPlanDetailMapp;

    @Autowired
    SysUserMapp userMapp;

    @Autowired
    private MessageNoticeMapp messageNoticeMapp;

    @Autowired
    private PointFlowMapp pointFlowMapp;

    @Override
    public Map<String, Object> query(TrainingPlanDetail trainingPlanDetail) {

        Map<String,Object> resultMap = new HashMap<>();
        try{
            if((trainingPlanDetail.getCurrentPage()+"") != null && (trainingPlanDetail.getPageSize()+"") != null){
                Page<TrainingPlanDetail> page = PageHelper.startPage(trainingPlanDetail.getCurrentPage(),trainingPlanDetail.getPageSize());
                List<TrainingPlanDetail> list = trainingPlanDetailMapp.query(trainingPlanDetail);
                resultMap.put("list",list);
                resultMap.put("total",page.getTotal());
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",resultMap);
    }

    @Override
    public Map<String, Object> add(TrainingPlanDetail trainingPlanDetail) {
        try{
            int returnInt = trainingPlanDetailMapp.insert(trainingPlanDetail);
            if(returnInt >= 0){
                return ResultUtil.returnSuccess("新增成功",null);
            }else{
                return ResultUtil.returnSuccess("新增失败",null);
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }

    }

    @Override
    public Map<String, Object> update(TrainingPlanDetail trainingPlanDetail) {
        try{
            int resultInt = trainingPlanDetailMapp.update(trainingPlanDetail);
            if(resultInt >= 0 ){
                return ResultUtil.returnSuccess("修改成功", null);
            }else{
                return ResultUtil.returnError("修改失败", null);
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("修改失败", null);
        }
    }

    @Override
    public Map<String, Object> delete(Map map) {
        try{
            if(map.get("ids") != null){
                for(Object id : (List)map.get("ids")){
                    trainingPlanDetailMapp.delete(id+"");
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("删除失败", null);
        }
        return  ResultUtil.returnSuccess("删除成功", null);
    }

    /**
     * 更新培训计划的状态 0：未参与 1：已参与  2 ：已完成
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> updatePlanStatus(Map map) {
        try{
            if(map.get("ids") != null && !"".equals(map.get("ids")) && map.get("planStatus") != null){
                for(Object id : (List)map.get("ids")){
                    Map<String,Object> param = new HashMap<>();
                    param.put("id",id+"");
                    param.put("planStatus",map.get("planStatus"));
                    trainingPlanDetailMapp.updateStatus(param);
                }
            }

//            if(map.get("planStatus") != null && !"1".equals(map.get("planStatus") + "")){
//                return ResultUtil.returnSuccess("修改成功", null);
//            }
//            /**
//             * 下达计划任务，任务状态为 "已参与"，发通知
//             */
//            ExtSysUser sysUser = new ExtSysUser();
//            sysUser.setType(map.get("type")+"");
//            sysUser.setPartyIds(map.get("partyIds")+"");
//            List<ExtSysUser> list = userMapp.findSysUserList(sysUser);
//            if(list == null || list.size() == 0){
//                return ResultUtil.returnSuccess("修改成功", null);
//            }
//            String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
//            for(ExtSysUser user : list){
//                MessageNotice msg = new MessageNotice();
//                msg.setTitle("电梯管理培训");
//                msg.setElevatoriMonId("111"); //web端对此值有校验，写死个假值
//                msg.setContent("您有一份电梯管理培训通知，请及时查看");
//                msg.setReceiveUserId(user.getId().toString());
//                msg.setIsRead("0");
//                msg.setNoticeTime(noticeTime);
//                msg.setSendUserId(map.get("beUserId")+"");
//                msg.setReceivePartyId(user.getPartyId().toString());
//                messageNoticeMapp.add(msg);
//            }

        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("修改失败", null);
        }finally {
            if(map.get("partyId") != null){
                String partyId = map.get("partyId").toString();
                String planStatus = map.get("planStatus").toString();
                String roleId = map.get("roleId").toString();
                String loggerType = map.get("loggerType").toString();
                String loggerUserId = map.get("loggerUserId").toString();
                if("2".equals(planStatus)){
                    // 维保或者使用
                    if (("1".equals(loggerType) && "17".equals(roleId)) || ("2".equals(loggerType) && "16".equals(roleId))) {
                        List<Integer> list =  (List)map.get("ids");

                        for(Integer id:list){
                            // 这块代码主要防止当上传已经完成，但是还是点击触发积分规则 ,先去查询当前主键是否以及有流水
                            PointFlow pointFlow = new PointFlow();
                            pointFlow.setIdentification("safety_education_training");
                            pointFlow.setExtendField(String.valueOf(id));
                            List<PointFlow> flows = pointFlowMapp.findList(pointFlow);

                            if (flows == null || flows.size() == 0) {
                                // 获取缓存
                                PointDefendInfoCache infoCache = new PointDefendInfoCache();
                                PointDefend defend = infoCache.getKeyByValue("safety_education_training");

                                // 获取当前用户，计算积分
                                Map<String, Object> maps = pointFlowMapp.findUserInfo(Long.valueOf(partyId));
                                long mark = (long) maps.get("mark");
                                int round = (int) (mark + defend.getMark());

                                // 更新主体单位用户信息总积分
                                String userId = maps.get("userId").toString();
                                int i1 = pointFlowMapp.updateMark(round, userId);
                                if (i1 != 0) {
                                    // 插入流水信息
                                    PointFlow flow = new PointFlow();
                                    flow.setOperationType(defend.getOperationType());
                                    flow.setOperationContent(defend.getOperationContent());
                                    flow.setUserName(maps.get("userName").toString());
                                    flow.setPartyName(maps.get("partyName").toString());
                                    flow.setIdentification(defend.getIdentification());
                                    flow.setMark(round);
                                    flow.setExtendField(String.valueOf(id));
                                    flow.setFunction("培训计划完成 + 单位积分");
                                    flow.setCreateBy(maps.get("userName").toString());
                                    flow.setCreateDate(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                                    pointFlowMapp.insertPointFlow(flow);

                                }

                                // 计算管理员积分并完成更新
                                Map<String, Object> usermaps = pointFlowMapp.findUserInfoByUserId(Long.valueOf(loggerUserId));
                                long usermark = (long) usermaps.get("mark");
                                int rounduser = (int) (usermark + defend.getMark());

                                // 更新主体单位用户信息总积分
                                String usersId = usermaps.get("userId").toString();
                                int i2 = pointFlowMapp.updateMark(rounduser, usersId);

                                String userUserName = usermaps.get("userName").toString();
                                String userPartyName = usermaps.get("partyName").toString();
                                SystemPointUtil.insertFlow(pointFlowMapp, i2, defend, rounduser, userUserName, userPartyName, "培训计划完成 + 用户积分");

                            }
                        }
                    }
                }
            }
        }
        return ResultUtil.returnSuccess("修改成功", null);
    }

    @Override
    public Map<String, Object> uploadTrainingPhoto(TrainingPlanDetail trainingPlanDetail) {
        try{
            trainingPlanDetailMapp.uploadTrainingPhoto(trainingPlanDetail);
            return ResultUtil.returnSuccess("成功", null);
        }catch(Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(), null);
        }
    }

    @Override
    public Map<String, Object> uploadCheckInTable(TrainingPlanDetail trainingPlanDetail) {
        try{
            trainingPlanDetailMapp.uploadCheckInTable(trainingPlanDetail);
            return ResultUtil.returnSuccess("成功", null);
        }catch(Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(), null);
        }
    }

    @Override
    public Map<String, Object> uploadSummaryStatement(TrainingPlanDetail trainingPlanDetail) {
        try{
            trainingPlanDetailMapp.uploadSummaryStatement(trainingPlanDetail);
            return ResultUtil.returnSuccess("成功", null);
        }catch(Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(), null);
        }
    }
}
